package com.zadtek.sharkRider.activity;

import android.annotation.SuppressLint;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.activity.adapter.MyMainAsyncTask;
import com.zadtek.sharkRider.activity.common.Common;
import com.zadtek.sharkRider.activity.common.Const;
import com.zadtek.sharkRider.activity.data.NewVersionData;
import com.zadtek.sharkRider.activity.data.QiangDanData;
import com.zadtek.sharkRider.activity.data.UserData;
import com.zadtek.sharkRider.frame.MyApplication;
import com.zadtek.sharkRider.receiver.ExampleUtil;
import com.zadtek.sharkRider.views.ShowMsgDialog;
import com.zadtek.sharkRider.views.SlidingMenu;
import com.umeng.update.UmengUpdateAgent;

public class MainActivity extends TabActivity implements
		OnCheckedChangeListener, OnClickListener {

	private SlidingMenu mMenu;

	private long exitTime = 0;

	private TabHost tabhost;
	private RadioGroup tab_radio;
	private RadioButton radio_newrw;	//新任务
	public static RadioButton radio_goqh, radio_gops; // 新任务,待取货,配送中

	private RadioGroup pushlay; // 是否开工
	private RadioButton workbut, orderno; // 开工1,收工2

	private Intent Ordernew, Orderqh, Orderps;

	private TextView ordoverid, usermoney, userset, paihbang,map; // 已完成的任务,账户余额,设置,排行榜、地图
	private TextView myname, myphone; // 姓名,手机
	
	private TextView sygordoverid;	//已完成的跑腿任务

	private SharedPreferences sp;

	private Handler mHandler;
	private QiangDanData sumcout;
	private UserData qsdata;	//骑士信息
	
	private String tagclose = "1";	//默认开工
	
	private NewVersionData versdata;	//新版本的信息

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// 友盟检查版本
//		com.umeng.common.Log.LOG = true;
		// 如果想程序启动时自动检查是否需要更新， 把下面两行代码加在Activity 的onCreate()函数里。
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		
		mMenu = (SlidingMenu) findViewById(R.id.menuid);
		tab_radio = (RadioGroup) findViewById(R.id.tab_radio);
		tab_radio.setOnCheckedChangeListener(this);
		tabhost = getTabHost();

		radio_newrw = (RadioButton) findViewById(R.id.radio_newrw);
		radio_goqh = (RadioButton) findViewById(R.id.radio_goqh);
		radio_gops = (RadioButton) findViewById(R.id.radio_gops);

		pushlay = (RadioGroup) findViewById(R.id.pushlay);
		workbut = (RadioButton) findViewById(R.id.workbut);
		orderno = (RadioButton) findViewById(R.id.orderno);

		Ordernew = new Intent(this, OrdernewActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		tabhost.addTab(tabhost
				.newTabSpec("Ordernew")
				.setIndicator(
						"",
						getResources().getDrawable(
								R.drawable.ordermenu_selector))
				.setContent(Ordernew));

		Orderqh = new Intent(this, OrderqhActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		tabhost.addTab(tabhost
				.newTabSpec("Orderqh")
				.setIndicator(
						"",
						getResources().getDrawable(
								R.drawable.ordermenu_selector_last))
				.setContent(Orderqh));

		Orderps = new Intent(this, OrderpsActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		tabhost.addTab(tabhost
				.newTabSpec("Orderps")
				.setIndicator(
						"",
						getResources().getDrawable(
								R.drawable.ordermenu_selector_last))
				.setContent(Orderps));

		tabhost.setCurrentTab(0);

		ordoverid = (TextView) findViewById(R.id.ordoverid);
		ordoverid.setOnClickListener(this);
		usermoney = (TextView) findViewById(R.id.usermoney);
		usermoney.setOnClickListener(this);
		userset = (TextView) findViewById(R.id.userset);
		userset.setOnClickListener(this);
		
		paihbang = (TextView) findViewById(R.id.paihbang);
		paihbang.setOnClickListener(this);
		
		sygordoverid = (TextView) findViewById(R.id.sygordoverid);
		sygordoverid.setOnClickListener(this);
		
		map = (TextView) findViewById(R.id.map);
		map.setOnClickListener(this);

		initViews();
		
		mHandler = new Handler() {
			@SuppressLint("NewApi")
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case Const.STATE_START_SUCCESS: // 获取数量成功
					sumcout = (QiangDanData) msg.obj;
					String status = sumcout.getStatus();
					if (status != null && status.equals("1")) {
						String xincount = sumcout.getNeworder();
						String noget = sumcout.getNoget();
						String nosend = sumcout.getNosend();
						radio_goqh.setText("待取货(" + noget + ")");
						radio_gops.setText("配送中(" + nosend + ")");
					}
					break;
				case Const.STATE_START_ERROR:
					// Common.DisplayToast(MainActivity.this, "通信失败,请检查网络!", 2);
					break;
				case Const.STATE_GETNUM_SUCC:	//获取骑士信息成功
					qsdata = (UserData) msg.obj;
					String qsstatus = qsdata.getStatus();
					if (qsstatus != null && qsstatus.equals("1")) {
						writeSp(qsdata);	//先存入缓存
						myname.setText(qsdata.getRealname());
						myphone.setText(qsdata.getPhone());
						String close = qsdata.getClose();
						setWordcheck(close);
					}
					break;
				case Const.STATE_SETQS_OPEN:	//设置骑士开收工成功
					QiangDanData data = (QiangDanData) msg.obj;
					String setstatus = data.getStatus();
					if (setstatus != null && setstatus.equals("1")) {
						//设置成功后,存入缓存
						sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
						Editor editor = sp.edit();
						editor.putString("close", tagclose);
						editor.commit();
						Common.DisplayToast(MainActivity.this, data.getMessage(), 1);
					} else {
						sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
						String close = sp.getString("close", "");
						setWordcheck(close);
					}
					break;
				case Const.STATE_SETQS_FAIL:	//设置骑士开收工失败
					sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
					String close = sp.getString("close", "");
					setWordcheck(close);
					break;
				case Const.STATE_GETVERSIONOK:	//获取新版本信息
					versdata = (NewVersionData) msg.obj;
					if (versdata != null) {
						//检测新版本
						checkVersion(MainActivity.this, versdata.getVersion());
					}
					break;
				}
			}
		};
		
		pushlay.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub
				RadioButton checkbut = (RadioButton) findViewById(pushlay
						.getCheckedRadioButtonId());
				tagclose = checkbut.getTag().toString();
				new MyMainAsyncTask(MainActivity.this, mHandler).execute(
						"setclose", tagclose);
			}
		});
		
		//获取用户信息
		if (Common.isNetworkConnected(MainActivity.this)) {
			new MyMainAsyncTask(MainActivity.this, mHandler)
					.execute("getversion");
			new MyMainAsyncTask(MainActivity.this, mHandler)
					.execute("getqsmsg");
		}

	}
	
	//检测新版本及更新
	private boolean checkVersion(Context context, String version) {
		boolean hasnew = false;
		PackageInfo pi = null;
		try {
			PackageManager pm = context.getPackageManager();
			pi = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			if(pi!=null) {
//				String versioname = pi.versionName;
				int versioncode = pi.versionCode;
				if(version!=null && !version.equals("")) {
					if(versioncode < Integer.parseInt(version)) {//有新的版本需要更新
						showDialog();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hasnew;
	}
	
	//弹出更新的版本
	private void showDialog() {
		if(versdata!=null) {
			String note = versdata.getNote();
			ShowMsgDialog MyDialog = new ShowMsgDialog(MainActivity.this, "发现新版本", note) {
				// 选择修改
				@Override
				public void doConfirmUp() {
					String filename = versdata.getDown_url();
					if(filename!=null && !filename.equals("")) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse(filename));
						startActivity(intent);
					}
					dismiss();
				}
			};
			MyDialog.show();
		}
	}

	// 设置用户的信息
	public void initViews() {
		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		String uname = sp.getString("uname", "");
		String phone = sp.getString("phone", "");
		String close = sp.getString("close", "");

		myname = (TextView) findViewById(R.id.myname);
		myphone = (TextView) findViewById(R.id.myphone);
		myname.setText(uname);
		myphone.setText(phone);
		setWordcheck(close);
	}
	
	//设置用户开收工
	public void setWordcheck(String close) {
		if(close.equals("1")) {	//开工
			workbut.setChecked(true);
			orderno.setChecked(false);
		} else {	//收工
			orderno.setChecked(true);
			workbut.setChecked(false);
		}
	}
	
	// 将用户信息写入缓存中
	private void writeSp(UserData userdata) {
		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putString("uid", userdata.getUid());
		editor.putString("uname", userdata.getRealname());
		editor.putString("phone", userdata.getPhone());
		editor.putString("account", userdata.getAccount());
		editor.putString("close", userdata.getClose());
		editor.putString("qsstatus", userdata.getQsstatus());
		editor.commit();
	}

	// 点击事件
	public void toggleMenu(View view) {
		mMenu.toggle();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		// 获取数量
		getmymsgCount();
		switch (checkedId) {
		case R.id.radio_newrw: // 新任务
			this.tabhost.setCurrentTabByTag("Ordernew");
			break;
		case R.id.radio_goqh: // 待取货
			this.tabhost.setCurrentTabByTag("Orderqh");
			break;
		case R.id.radio_gops: // 配送中
			this.tabhost.setCurrentTabByTag("Orderps");
			break;
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.ordoverid: // 已完成的任务
			Intent intent = new Intent(this, OrderOverActivity.class);
			startActivity(intent);
			break;
		case R.id.usermoney: // 账户余额
			Intent intentye = new Intent(this, UserMoneyActivity_.class);
			startActivity(intentye);
			break;
		case R.id.userset: // 账户余额
			Intent intentset = new Intent(this, SettingActivity.class);
			startActivity(intentset);
			break;
		case R.id.sygordoverid:	//已完成的跑腿任务
			Intent intentsyg = new Intent(this, SygOrderOverActivity.class);
			startActivity(intentsyg);
			break;
		case R.id.paihbang:	//我的统计
			Intent paih = new Intent(this, MytjFragment.class);
			startActivity(paih);
			break;
		case R.id.map:	//我的统计
			Intent map = new Intent(this, UserAddressMap.class);
			startActivity(map);
			break;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 获取数量
		getmymsgCount();
	}

	// 得到任务列表数据
	public void getmymsgCount() {
		if (Common.isNetworkConnected(MainActivity.this)) {
			sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
			String uid = sp.getString("uid", "");
			if (uid != null && !uid.equals("")) {
				new MyMainAsyncTask(MainActivity.this, mHandler).execute("getsum");
			}
		}
	}

	
	/**
	 * 捕捉返回事件按钮
	 */

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				this.exitApp();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				// 响应事件的具体代码
				this.exitApp();
			}
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	/**
	 * 退出程序
	 */
	private void exitApp() {
		// 判断2次点击事件时间
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT)
					.show();
			exitTime = System.currentTimeMillis();
		} else {
			MyApplication.getInstace().exit();
		}
	}

	// for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.zadtek.sharkRider.activity.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
				String messge = intent.getStringExtra(KEY_MESSAGE);
				String extras = intent.getStringExtra(KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder();
				showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
				if (!ExampleUtil.isEmpty(extras)) {
					showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
				}
			}
		}
	}

}
